from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    # 不需要显式添加id字段，Django会自动创建
    openid = models.CharField(max_length=128, unique=True, null=True, blank=True)
    username = models.CharField(max_length=150, null=True, unique=True)
    # 不需要再次声明password字段，因为AbstractUser类已经包含了password字段
    # email字段已在AbstractUser中定义，只需指定null和blank即可
    email = models.EmailField(null=True, blank=True)
    phone_number = models.CharField(max_length=15, null=True, blank=True)
    real_name = models.CharField(max_length=128, null=True, blank=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    role_type = models.CharField(max_length=50, null=True, blank=True)
    avatar = models.URLField(null=True, blank=True)
    gender = models.CharField(max_length=10, null=True, blank=True)
    birthday = models.DateField(null=True, blank=True)
    address = models.CharField(max_length=255, null=True, blank=True)
    # 新增加的微信字段
    nickname = models.CharField(max_length=64, null=True, blank=True)
    sex = models.PositiveSmallIntegerField(choices=((0, '未知'), (1, '男'), (2, '女')), null=True, blank=True)
    language = models.CharField(max_length=32, null=True, blank=True)
    city = models.CharField(max_length=32, null=True, blank=True)
    province = models.CharField(max_length=32, null=True, blank=True)
    country = models.CharField(max_length=32, null=True, blank=True)
    headimgurl = models.URLField(null=True, blank=True)
    privilege = models.JSONField(default=list, blank=True, null=True)  # 使用可调用的默认值
    unionid = models.CharField(max_length=128, null=True, blank=True)

    # last_login字段已经在AbstractBaseUser中，不需要重复声明

    # 如果你没有特别需要覆盖save()方法，也可以省略这个方法
    # def save(self, *args, **kwargs):
    #     super(User, self).save(*args, **kwargs)

    @classmethod
    def create_or_update_from_wechat(cls, wechat_data):
        user, created = cls.objects.update_or_create(
            openid=wechat_data['openid'],
            defaults={
                'nickname': wechat_data.get('nickname', ''),
                'sex': wechat_data.get('sex', 0),
                'language': wechat_data.get('language', ''),
                'city': wechat_data.get('city', ''),
                'province': wechat_data.get('province', ''),
                'country': wechat_data.get('country', ''),
                'headimgurl': wechat_data.get('headimgurl', ''),
                'privilege': wechat_data.get('privilege', []),
                'unionid': wechat_data.get('unionid', ''),
            }
        )
        return user
